#!/bin/sh
#
# sshd        Starts sshd.
#
SSHD=/usr/sbin/sshd
SSH_KEYGEN=/usr/bin/ssh-keygen
LOCK=/var/lock/sshd

for file in ${SSHD} ${SSH_KEYGEN}; do
	[ -f ${file} ] || {
		echo "$0: The ${file} program does not exist, exiting."
		exit 1
	}
done

umask 077

start() {
	[ -f ${LOCK} ] && {
		echo "sshd already started (${LOCK} file present)."
		exit 1
	}
	if ! [ -z "$(${SSHD} -t 2>&1)" ]; then
		# sshd will not start with current config,
		echo "Generating a new set of ssh keys."
		for key_type in rsa dsa ecdsa ed25519; do
			key_file=/etc/ssh/ssh_host_${key_type}_key
			# If keys exist, delete them, because they are
			# not valid and ssh-keygen will not overwrite them.
			echo "${key_file}..."
			rm -f ${key_file} ${key_file}.pub
			${SSH_KEYGEN} -q -f ${key_file} -N '' -t ${key_type}
		done
	fi

	printf "Starting sshd: "
	${SSHD}
	touch ${LOCK}
	echo "OK"
}
stop() {
	printf "Stopping sshd: "
	killall $(basename ${SSHD})
	rm -f ${LOCK}
	echo "OK"
}
restart() {
	stop
	start
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|reload)
	restart
	;;
  *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
esac

